//% color="#FF6347" iconWidth=45 iconHeight=45
namespace LLMAssistant {

    //% block="初始化模型 API地址[API_URL] API密钥[API_KEY] 模型[MODEL]" blockType="command"
    //% API_URL.shadow="string" API_URL.defl="https://api.deepseek.com"
    //% API_KEY.shadow="string" API_KEY.defl="api_key"
    //% MODEL.shadow="string" MODEL.defl="deepseek-chat"
    export function initializeLLM(parameter: any) {
        const apiUrl = parameter.API_URL.code;
        const apiKey = parameter.API_KEY.code;
        const model = parameter.MODEL.code;

        Generator.addImport(`import requests\nimport json`);
        
        Generator.addCode(`
class LLMChat:
    def __init__(self):
        base_url = ${apiUrl}.rstrip('/')
        self.api_url = f"{base_url}/chat/completions"
        self.api_key = ${apiKey}
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        self.messages = [{"role": "user", "content": "回答简短，不要出现emoji表情"}]
        self.model = ${model}

    def chat(self, user_input):
        
        self.messages.append({"role": "user", "content": user_input})
        
        payload = {
            "model": self.model,
            "messages": self.messages
        }
        try:
            response = requests.post(
                url=self.api_url,
                headers=self.headers,
                data=json.dumps(payload)
            )
            if response.status_code == 200:
                response_data = response.json()
                ai_response = response_data['choices'][0]['message']['content']
                self.messages.append({"role": "assistant", "content": ai_response})
                return ai_response
            else:
                return f"Error: {response.status_code} - {response.text}"
        except Exception as e:
            return f"Exception: {str(e)}"

global bot
bot = LLMChat()`);
    }

    //% block="发送消息[MESSAGE] 并返回响应" blockType="reporter"
    //% MESSAGE.shadow="string" MESSAGE.defl="你好"
    export function sendMessage(parameter: any, block: any) {
        const message = parameter.MESSAGE.code;
        Generator.addCode(`bot.chat(${message})`);
    }
}